package com.xiaoli.mss.file.mysql;

import com.xiaoli.mss.file.FileServer;
import com.xiaoli.mss.file.mysql.mapper.FilePoMapper;
import com.xiaoli.mss.file.mysql.po.FilePo;
import com.xiaoli.mss.util.UuidUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 使用mysql存储文件，降低运维人员难度
 *
 */
@Service("fileServer")
public class MysqlDBFileServer implements FileServer {
    @Autowired
    private FilePoMapper filePoMapper;
    @Override
    public String save(String filename, InputStream is)  {
        FilePo sysFilePo = new FilePo();
        sysFilePo.setId(UuidUtils.uuid());
        Integer length = 0;
        try {
            length = is.available();
        } catch (IOException e) {
            e.printStackTrace();
        }

        byte[] buffer = new byte[length];

        try {
            is.read(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }

        sysFilePo.setFile(buffer);
        filePoMapper.insert(sysFilePo);
        return sysFilePo.getId();
    }

    @Override
    public void delete(String fileId) {
        filePoMapper.deleteByPrimaryKey(fileId);
    }

    @Override
    public InputStream get(String fileId) {
        FilePo file = filePoMapper.selectByPrimaryKey(fileId);
        if(file == null){
            return null;
        }else{
            InputStream is = new ByteArrayInputStream(file.getFile());
            return is;
        }
    }

    @Override
    public String saveMultipartFile(MultipartFile multipartFile) {
        byte[] buffer = null;
        try {
            buffer = multipartFile.getBytes();
        } catch (IOException e) {
            e.printStackTrace();
        }

        FilePo sysFilePo = new FilePo();
        sysFilePo.setId(UuidUtils.uuid());
        sysFilePo.setFile(buffer);
        filePoMapper.insert(sysFilePo);
        return sysFilePo.getId();
    }
}
